package com.yqh.service.impl;

import com.yqh.config.CaptureConfig;
import com.yqh.dao.UserDao;
import com.yqh.dto.UserDTO;
import com.yqh.entity.User;
import com.yqh.exception.CustomException;
import com.yqh.service.UserService;
import com.yqh.utils.JwtTokenUtil;
import com.yqh.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;


    /**
     * 登录
     *
     * @param key
     * @param userDTO 用户及密码
     */
    @Override
    public UserLoginVO login(UserDTO userDTO) {
        // 判断验证码对不对
        if (!userDTO.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(userDTO.getKey()))) {
            // 如果不相等，说明验证不通过
            throw new CustomException("验证码不正确");
        }
        User findUser = userDao.findByUserNameAndPassword(userDTO.getUserName(), userDTO.getPassword());
        if (findUser == null) {
            // 未查到用户，向前端报错
            throw new CustomException("用户名或密码错误请重新输入");
        } else {
            // 查到用户，生成 token 并一起传回前端
            String token = JwtTokenUtil.getToken(findUser.getUserId(), findUser.getPassword());
            return new UserLoginVO(findUser.getUserId(), findUser.getUserName(), token);
        }
    }

    /**
     * 注册
     *
     * @param user 用户及密码
     */
    @Override
    public void register(User user) {
        User findUser = userDao.findByUserName(user.getUserName());
        if (findUser == null) {
            userDao.addUser(user.getUserName(), user.getPassword());
        } else {
            throw new CustomException("用户名已重复，请重新输入");
        }
    }

    // todo 未使用

    /**
     * 通过用户id查询用户信息
     *
     * @param UserId 用户id
     * @return 用户信息
     */
    @Override
    public User findUserById(Integer UserId) {
        return userDao.findUserById(UserId);
    }
}
